package com.scalar.chiptrack.adaptor.ikanos.asem;

import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.jobs.JobHandler;

import javax.mail.Message;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Address;
import javax.mail.Part;
import java.util.Date;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;

/**
 * User: ChandraSekhar
 * Date: Jul 21, 2008
 * Time: 12:05:12 PM
 */
public class ASEMPOP3Adaptor extends JobHandler implements AdaptorConstants
{
    private static final String HOST               = "207.155.250.20";

    public static final String FILE_NAME_WIP 	   = "ASEM_WIP_REPORT";
    public static final String FILE_NAME_SHIP 	   = "ASEM_SHIP_REPORT";

    public static final String ADAPTOR_NAME        = "ASEM_WIP";

    private static final String SUBJECT_WIP        = "Ikanos daily report";
    private static final String SUBJECT_DAILY_SHIP = "SHIPMENT REPORT";

    private Logger m_adaptorLogger      = null;
    private String m_dataOutputDir      = null;
    private String m_username           = null;
    private String m_password           = null;
    private int    m_adaptor_id         = -1;

    public ASEMPOP3Adaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_ASEM, LOCATION_TYPE_ASSEMBLY);

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();

            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger = AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_ASEM );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch (Exception se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading ASEM Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
    }

    //Main Method
    public static void main(String[] args) throws Exception
    {
        new ASEMPOP3Adaptor().execute();
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
            // Step 1
             // prints the version of Adaptor
            AdaptorUtils.printHeader( VENDOR_NAME_ASEM, CONSTANT_ADAPTOR );

            // Step 2
            // removes the old files out side done directory
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            // Step 3
            //Retrive All the Messages
            Message[] messages = AdaptorUtils.getAllPOP3InboxMessages( HOST, m_username, m_password);
            // Step 4
            // Retrieve & Saves the latest message
            AdaptorUtils.readLatestMessage( m_adaptor_id, messages, SUBJECT_WIP,    m_dataOutputDir, FILE_EXTN_XLS,  FILE_NAME_WIP );
            readLatestMessage( m_adaptor_id, messages, SUBJECT_DAILY_SHIP,   m_dataOutputDir, FILE_EXTN_XLS, FILE_NAME_SHIP );
        }
        catch (Exception e)
        {
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id);
            System.out.println("Exception while trying to connect and read data from " + HOST +" site: " + e);
            log("Exception while trying to connect and read data from " + HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    public void readLatestMessage( int m_adaptor_id, Message[] message, String subject, String outputDir, String fileType, String appendFileName ) throws Exception
    {
        Message wipMessage  = null;
        if ( message == null || message.length == 0 )
        {
            return;
        }
        BodyPart part = null;
        Multipart mp  = null;
        /*To download Wip sheet */
        for (int i = 0; i < message.length; i++)
        {
            //To get the only  : WIP Report with subject
			if ( message[i].getSubject() != null && message[i].getSubject().trim().length() > 0
                    && ( message[i].getSubject().startsWith( subject ) || message[i].getSubject().endsWith( subject ) || message[i].getSubject().indexOf(subject) != -1  ) )
            {
                Address address[] = message[i].getFrom();

                for( int j = 0; j < address.length ; j++ )
                {
                    //System.out.println( "From  :=  " + address[j].toString() );
                    //to get the only from address
                    if( address[j].toString() != null && address[j].toString().indexOf( "Autonotification@asemal.com.my") != -1 )
                    {
                        log( "From  :=  " + address[j].toString() );

                        Object obj = message[i].getContent();

                        if ( wipMessage == null )
                        {
                            if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                            {
                                 wipMessage = message[i];
                            }
                            else
                            {
                                if (obj instanceof Multipart )
                                {
                                   mp = (Multipart) obj;

                                    for ( int m = 0; m < mp.getCount(); m++ )
                                    {
                                        part = mp.getBodyPart(m);
										log(" WHEN NULL part.getDisposition()" + part.getDisposition() );
                                        if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( BodyPart.ATTACHMENT ) || part.getDisposition().equals( BodyPart.INLINE ))  )
                                        {
                                            wipMessage = message[i];
                                            break;
                                        }
                                        else if ( part.getFileName() != null )
                                        {
                                            wipMessage = message[i];
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            java.util.Date date1 = wipMessage.getSentDate();
                            java.util.Date date2 = null;

                            if ( message[i].getDisposition() != null && ( message[i].getDisposition().equals( Message.ATTACHMENT ) || message[i].getDisposition().equals( Message.INLINE ) ) && message[i].getFileName() != null )
                            {
                                 date2 = message[i].getSentDate();
                            }
                            else
                            {
                                if (obj instanceof Multipart )
                                {
                                   mp = (Multipart) obj;

                                    for ( int m = 0; m < mp.getCount(); m++ )
                                    {
                                        part = mp.getBodyPart(m);

                                        if ( ( part.getDisposition() != null ) && ( part.getDisposition().equals( BodyPart.ATTACHMENT ) || part.getDisposition().equals( BodyPart.INLINE ))  )
                                        {
                                            date2 = message[i].getSentDate();
                                            break;
                                        }
                                        else if ( part.getFileName() != null )
                                        {
                                            date2 = message[i].getSentDate();
                                            break;
                                        }
                                    }
                                }
                            }

                            if (date1 != null && date2 != null)
                            {
                                if (date2.compareTo(date1) > 0)
                                {
                                    wipMessage = message[i];
                                }
                            }

                        }
                    }
                }
            }
        }

        // To process the Message and download the files
        if ( wipMessage != null )
        {
            downLoadMessage( m_adaptor_id, wipMessage, subject, outputDir, fileType, appendFileName );
            wipMessage = null;
        }
        else
        {
             log("\n\n****The Requested Subject was not found in INBOX***" + subject + "\n");
             System.out.println("\n\n****The Requested Subject was not found in INBOX***" + subject+"\n" );
        }
    }

	public void downLoadMessage( int m_adaptor_id , Message message, String subject , String outputDir, String fileType, String appendFileName) throws Exception
    {
        if ( message == null )
        {
            return;
        }

        Multipart mp        = null;
        BodyPart part           = null;
        String disposition  = null;
        InputStream inputStream = null;

        String fileName     = null;
        String fileExtn    = null;
        log("Processing  Message for "+ subject + " .......");
        System.out.println("Processing  Message for "+ subject + " .......");

        try
        {
            //IF BLOCK EXECUTES ONLY FOR OSE WIP FILE
            if ( message.getDisposition() != null && ( message.getDisposition().equals( Message.ATTACHMENT ) || message.getDisposition().equals( Message.INLINE ) ) && message.getFileName() != null )
            {
                fileName = message.getFileName().replaceAll("\\?", "").replaceAll("=5F=5F", "_").replaceAll("=2E", ".");
                String messgaeFileName = fileName;
                if ( fileName.indexOf("PCCWIPSTD") != -1 )
                {
                    fileName =  fileName.substring( fileName.indexOf("PCCWIPSTD") , fileName.lastIndexOf(".") );
                    fileExtn  = messgaeFileName.substring( messgaeFileName.lastIndexOf(".") + 1 , messgaeFileName.length() );
                }
                else
                {
                   fileName =  fileName.substring( 0 , fileName.lastIndexOf(".") );
                   fileExtn  = messgaeFileName.substring( messgaeFileName.lastIndexOf(".") + 1 , messgaeFileName.length() );
                }
                //System.out.println("fileExtn = " + fileExtn);
                inputStream = message.getInputStream();
				if ( fileName != null )
				{
					fileName = fileName.toUpperCase();

					if ( m_adaptor_id > 0 )
					{
						AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , fileName, fileExtn, StringUtils.formatDateToString( message.getSentDate(), "MM/dd/yyyy HH:mm:ss") ) ;
					}
					if ( appendFileName != null )
					{											
						fileName = appendFileName +"_" + fileName;
					}
					log("\tDownloding "+subject+"................. ");
					System.out.println("\tDownloding "+subject+"................. ");

					AdaptorUtils.saveAsBinaryFile( new BufferedInputStream(inputStream), outputDir, fileName, fileExtn, true /* append time stamp */);
					System.out.println("Done.\n"  );
					fileName = null;
				}
              
            }
            else
            {
				log("IN ELSE BLOCK");
                Object obj = message.getContent();

                if (obj instanceof Multipart )
                {
                    mp = (Multipart) obj;
					log("mp.getCount()" + mp.getCount() );
                    for ( int i = 0; i < mp.getCount(); i++ )
                    {
                        part = mp.getBodyPart(i);

                        disposition = part.getDisposition();
                        log("part.disposition()"+ disposition );
						log("part.getFileName()"+ part.getFileName() );
                        //taking the wip & ASSEMBLY attachmentS
                        //if ( ( disposition != null ) && ( disposition.equals( BodyPart.ATTACHMENT ) || disposition.equals( BodyPart.INLINE ))  )
                        //{
							log("part.getFileName()"+ part.getFileName() );
                            if ( part.getFileName() != null && part.getFileName().toUpperCase().indexOf("PDF") < 1 )
                            {
                                if ( "summary".equalsIgnoreCase(fileType) )
                                {
                                      fileExtn = FILE_EXTN_TXT;
                                }
                                if ("IKANOS CP DATA".equalsIgnoreCase( subject ) )
                                {
                                    if ( part.getFileName().indexOf("sum.txt") != -1 )
                                    {
                                        fileName =  part.getFileName().substring( 0 , part.getFileName().lastIndexOf(".") );
                                        fileExtn  = part.getFileName().substring( part.getFileName().lastIndexOf(".") + 1 , part.getFileName().length() );
                                    }
                                }
                                else
                                {
                                    fileName =  part.getFileName().substring( 0 , part.getFileName().lastIndexOf(".") );
                                    fileExtn  = part.getFileName().substring( part.getFileName().lastIndexOf(".") + 1 , part.getFileName().length() );
                                }
                                
                                inputStream = part.getInputStream();
                                if ( appendFileName != null && "SCK_DROP_SHIP".equalsIgnoreCase(appendFileName))
                                {
                                    if ( part.getFileName().indexOf(".TXT") != -1 )
                                    {
                                        fileName = null;
                                    }
                                }
                                if ( appendFileName != null && "SCM_DROP_SHIP".equalsIgnoreCase(appendFileName))
                                {
                                    if ( part.getFileName().indexOf("COMM") != -1 )
                                    {
                                        fileName = null;
                                    }
                                }
                                if ( fileName != null && fileName.indexOf("Legend Silicon Daily Transaction report") == -1 )
                                {
                                    fileName = fileName.replaceAll("-", "_").toUpperCase().replaceAll("LEGEND", "L").replaceAll("SILICON", "S").replaceAll("INVENTORY", "INV");

                                    if ( m_adaptor_id > 0 )
                                    {
                                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , fileName, fileExtn, StringUtils.formatDateToString( message.getSentDate(), "MM/dd/yyyy HH:mm:ss") ) ;
                                    }

                                    if ( appendFileName != null )
                                    {											
                                        fileName = appendFileName +"_" + fileName;
                                    }

                                    log("\tDownloding "+subject+"................. ");
                                    System.out.println("\tDownloding "+subject+"................. ");

                                    AdaptorUtils.saveAsBinaryFile( new BufferedInputStream(inputStream), outputDir, fileName, fileExtn, true /* append time stamp */);
                                    fileName = null;
                                    System.out.println("Done.\n"  );
                                }
                            }
                        //}
                    } //FOR LOOP
                }//IF FOR CHECKING ONLY MULTI PART      
            }
        }
        catch( Exception e)
        {
            System.out.println("EXception Occcuered while Proceess and downloading the Messge:" + e );
            e.printStackTrace();
            throw e;
        }
        finally
        {
            if ( inputStream != null )
            {
                try
                {
                    inputStream.close();
                    inputStream = null;
                }
                catch (IOException e)
                {
                }
            }
        }
    }

    /**
     *
     * @param message
     */
    private void log(String message)
    {

        if (message == null) return;

        if (m_adaptorLogger != null)
        {
            synchronized (m_adaptorLogger)
            {
                m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}